/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.web.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.mapper.UserMapper;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.web.entity.WxAgents;
import com.jeeplus.modules.web.entity.WxAgentsCommissionRecord;
import com.jeeplus.modules.web.mapper.WxAgentsMapper;
import com.jeeplus.modules.web.service.WxAgentsCommissionRecordService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.*;

/**
 * 分销记录Controller
 * @author rongjie
 * @version 2017-09-04
 */
@Controller
@RequestMapping(value = "${adminPath}/web/wxAgentsCommissionRecord")
public class WxAgentsCommissionRecordController extends BaseController {

	@Autowired
	private WxAgentsCommissionRecordService wxAgentsCommissionRecordService;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private WxAgentsMapper wxAgentsMapper;
	
	@ModelAttribute
	public WxAgentsCommissionRecord get(@RequestParam(required=false) String id) {
		WxAgentsCommissionRecord entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = wxAgentsCommissionRecordService.get(id);
		}
		if (entity == null){
			entity = new WxAgentsCommissionRecord();
		}
		return entity;
	}
	
	/**
	 * 分销记录列表页面
	 */
	@RequiresPermissions("web:wxAgentsCommissionRecord:list")
	@RequestMapping(value = {"list", ""})
	public String list(Model model) {
		WxAgents wxAgents = new WxAgents();
		wxAgents.setStatus(1);
		User currentUser = UserUtils.getUser();
		WxAgents currentAgents = null;
		List<WxAgents> list = null;
		if (!currentUser.getId().equals("1")) {// 不是管理员，权限过滤
			currentAgents = wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
			Map<String, List<WxAgents>> listmap = recursionAgents(Integer.parseInt(currentAgents.getId()));
			model.addAttribute("childList", listmap.get("childList"));
			model.addAttribute("shopList", listmap.get("shopList"));
		} else {
			wxAgents.setAgentLevel(0);
			list = wxAgentsMapper.selectList(wxAgents);
			model.addAttribute("list", list);
		}
		model.addAttribute("currentAgents", currentAgents);
		return "modules/web/wxAgentsCommissionRecordList";
	}
	
		/**
	 * 分销记录列表数据
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgentsCommissionRecord:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(WxAgentsCommissionRecord wxAgentsCommissionRecord, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WxAgentsCommissionRecord> page = wxAgentsCommissionRecordService.findPage(new Page<WxAgentsCommissionRecord>(request, response), wxAgentsCommissionRecord); 
		return getBootstrapData(page);
	}


	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgentsCommissionRecord:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(WxAgentsCommissionRecord wxAgentsCommissionRecord, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "分销记录"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WxAgentsCommissionRecord> page = wxAgentsCommissionRecordService.findPage(new Page<WxAgentsCommissionRecord>(request, response, -1), wxAgentsCommissionRecord);
    		new ExportExcel("分销记录", WxAgentsCommissionRecord.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出分销记录记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("web:wxAgentsCommissionRecord:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WxAgentsCommissionRecord> list = ei.getDataList(WxAgentsCommissionRecord.class);
			for (WxAgentsCommissionRecord wxAgentsCommissionRecord : list){
				try{
					wxAgentsCommissionRecordService.save(wxAgentsCommissionRecord);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条分销记录记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条分销记录记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入分销记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/web/wxAgentsCommissionRecord/?repage";
    }
	
	/**
	 * 下载导入分销记录数据模板
	 */
	@RequiresPermissions("web:wxAgentsCommissionRecord:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "分销记录数据导入模板.xlsx";
    		List<WxAgentsCommissionRecord> list = Lists.newArrayList(); 
    		new ExportExcel("分销记录数据", WxAgentsCommissionRecord.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/web/wxAgentsCommissionRecord/?repage";
    }

	private Map<String, List<WxAgents>> recursionAgents(Integer parentId) {
		WxAgents wxAgents = new WxAgents();
		wxAgents.setParentId(parentId);
		wxAgents.setStatus(1);

		List<WxAgents> childList = wxAgentsMapper.selectList(wxAgents);
		List<WxAgents> shopList = new ArrayList<WxAgents>();

		for (Iterator<WxAgents> iterator = childList.iterator(); iterator.hasNext();) {
			WxAgents elem = (WxAgents) iterator.next();
			if (elem.getAgentLevel() == 3) {
				shopList.add(elem);
				iterator.remove();
			} else if (elem.getId().equals(String.valueOf(parentId))) {
				iterator.remove();
			}
		}
		HashMap<String, List<WxAgents>> hashMap = new HashMap<>();
		hashMap.put("childList", childList);
		hashMap.put("shopList", shopList);
		return hashMap;

	}

}